﻿//using System;
//using System.Collections.Concurrent;
//using System.Collections.Generic;
//using System.Data;
//using System.Data.SqlClient;
//using System.Linq;
//using System.Threading.Tasks;
//using Cache.CSRedis;
//using Dapper;
//using DotNetCore.CAP;
//using Microsoft.AspNetCore.Http;
//using Microsoft.AspNetCore.Mvc;
//using Microsoft.EntityFrameworkCore.Internal;
//using MySql.Data.MySqlClient;
//using Product.Common;
//using Product.Common.Dto;

//namespace ProductWebApi.Controllers
//{
//    [Route("api/product/v1/[controller]/[action]")]
//    [ApiController]

//    public class StockController : ControllerBase
//    {
//        private readonly IRedisHelper _redisHelper;
//        private readonly ICapPublisher _capPublisher;
//        private readonly ConcurrentDictionary<string, TaskCompletionSource<string>> callbackMapper =
//            new ConcurrentDictionary<string, TaskCompletionSource<string>>();
//        public StockController()
//        {
//        }

//        /// <summary>
//        /// 扣减库存
//        /// http://localhost:24748//api/product/v1/Stock/DeductionStock
//        /// </summary>
//        /// <param name="productId"></param>
//        /// <param name="productNumber"></param>
//        /// <returns></returns>
//        [HttpPost]
//        public async Task<ResponseResult<string>> DeductionStock(List<SkuDto> skuList)
//        {
//            if (skuList.Any())
//            {
//                return new ResponseResult<string>() { IsSucceed = false, Message = "sku不能为空!" };
//            }

//            var connectionString = ConfigurationHelper.GetConnectionString();
        
//            using (var connection = new MySqlConnection(connectionString))
//            {
//                try
//                {
//                    if (connection.State == ConnectionState.Closed)
//                    {
//                        await connection.OpenAsync().ConfigureAwait(false);
//                    }
//                    var sql = string.Empty;
//                    foreach (var sku in skuList)
//                    {
//                        if (string.IsNullOrWhiteSpace(sku.SkuId))
//                        {
//                            return new ResponseResult<string>() { IsSucceed = false, Message = $"{sku.SkuId}:skuId不能为空!" };
//                        }

//                        if (sku.SkuQuantity == 0)
//                        {
//                            return new ResponseResult<string>() { IsSucceed = false, Message = $"{sku.SkuId}:sku数量不能为0!" };
//                        }
//                        sql += $"UPDATE t_sku SET Stock=Stock - {sku.SkuQuantity} where Id = {sku.SkuId} AND  Stock > {sku.SkuQuantity};";
//                    }
                    
//                    var transaction = await connection.BeginTransactionAsync();
//                    try
//                    {
//                        var i = await connection.ExecuteAsync(sql);
//                        await transaction.CommitAsync();
//                        if (i > 0)
//                        {
//                            return new ResponseResult<string>() { IsSucceed = true, Message = "扣减库存成功!" };
//                        }
//                        else
//                        {
//                            return new ResponseResult<string>() { IsSucceed = false, Message = "扣减库存失败!" };
//                        }                       
//                    }
//                    catch (Exception ex)
//                    {
//                        await transaction.RollbackAsync();
//                        await transaction.DisposeAsync();
//                        throw new Exception(ex.Message);
//                    }
                   
//                }
//                catch (Exception ex)
//                {
//                    throw new Exception($"扣减库存失败！{skuList.Select(e=>e.SkuId).Join(",")}{ex.Message}");
//                }
//            }
//        }

//        /// <summary>
//        /// 扣减库存(cap)
//        /// </summary>
//        /// <param name="input"></param>
//        /// <returns></returns>
//        [HttpPost]
//        [Subscribe("DeductionStockEvent")]
////        public async Task<ExecuteMethodResult> DeductionStockByCap(DeductionStockDto input)
////        {
////            if (string.IsNullOrWhiteSpace(input.ProductId))
////            {
////                return await Task.FromResult(ExecuteMethodResult.Failed("产品Id不能为空！"));
////            }
////            if (input.ProductNumber <= 0)
////            {
////                return await Task.FromResult(ExecuteMethodResult.Failed("产品数量必须大于零！"));
////            }
////            if (string.IsNullOrWhiteSpace(input.OrderUniqueCode))
////            {
////                return await Task.FromResult(ExecuteMethodResult.Failed("订单号不能为空！"));
////            }
////            var connectionString = ConfigurationHelper.GetConnectionString();
////            //用Redis 实现幂等，忽略了存储Redis失败的情况，最好使用本地事务去重表，添加唯一约束
////            var existsHashKey = await _redisHelper.ExistsHashKeyAsync("DeductionStockIdempotent", input.OrderUniqueCode);
////            if (!existsHashKey)
////            {
////                using (var connection = new MySqlConnection(connectionString))
////                {
////                    try
////                    {
////                        if (connection.State == ConnectionState.Closed)
////                        {
////                            await connection.OpenAsync().ConfigureAwait(false);
////                        }

////                        string sql = "update ProductStock set ProductStockNumber=ProductStockNumber - @ProductNumber where ProductStockNumber >0 and ProductId=@ProductId";
////                        var i = await connection.ExecuteAsync(sql, new { input.ProductNumber, input.ProductId });
////                        if (i > 0)
////                        {
////                            await _redisHelper.HashSetEntityAsync("DeductionStockIdempotent", input.OrderUniqueCode, e => e.ToString());
////                            return await Task.FromResult(ExecuteMethodResult.Success());
////                        }
////                        else
////                        {
////                            return await Task.FromResult(ExecuteMethodResult.Failed("扣减库存失败！"));
////                        }
////                    }
////#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
////                    catch (Exception ex)
////#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
////                    {
////                        return await Task.FromResult(ExecuteMethodResult.Failed("扣减库存异常！"));
////                    }
////                }
////            }
////            else
////            {
////                _redisHelper.StringSet("repeatOrderUniqueCode", input.OrderUniqueCode);
////                return await Task.FromResult(ExecuteMethodResult.Success());
////            }
////        }

//        [HttpGet]
//        public async Task<ActionResult> DescStock()
//        {
//            //await Task.Run(() =>
//            //{
//            //    var script = @"local stock = redis.call('get', KEYS[1]) 
//            //                if stock == '0' then
//            //                  return 0;
//            //                end
//            //                  redis.call('decr', KEYS[1])
//            //                  return 1";
//            //    var remainderProductStock = _redisHelper.Lua(script, "ProductStock");

//            //});

//            await _redisHelper.IncrBy("ProductStock", -1);
//            return Ok();
//        }


//        #region CAP 消息补偿
//        [HttpGet]
//        public async Task Publish()
//        {
//            var correlationId = Guid.NewGuid().ToString();
//            await _capPublisher.PublishAsync("TestPublish", correlationId, "PublishCallbackName");
//        }

//        [HttpGet]
//        [CapSubscribe("TestPublish", Group = "TestPublish")]
//        public ResponseResult<string> Subscriber(string correlationId)
//        {
//            return new ResponseResult<string>() { IsSucceed = true, Message = "测试", Result = correlationId };
//        }
//        /// <summary>
//        /// 消费端异常时可以做补偿事件
//        /// </summary>
//        /// <param name="result"></param>
//        /// <returns></returns>
//        [HttpGet]
//        [CapSubscribe("PublishCallbackName", Group = "PublishCallbackName")]
//        public Task PublishCallbackName(ResponseResult<string> result)
//        {
//            return Task.CompletedTask;
//        }
//        #endregion
//    }
   
//}